<template>
  <div
    ref="sliderRef"
    class="relative w-full h-16 flex items-center justify-center select-none cursor-pointer"
    @mousedown="onMouseDown"
    @touchstart="onTouchStart"
  >
    <!-- 刻度轨道 -->
    <div ref="trackRef" class="w-[90%] h-1 bg-gray-300 relative">
      <!-- 刻度线 -->
      <div class="absolute top-0 left-0 w-full h-5">
        <!-- 生成刻度线，确保0在中间 -->
        <template v-for="i in totalSteps" :key="i">
          <div
            :class="[
              'absolute bg-gray-400',
              (i + min - 1) % 10 === 0
                ? 'h-5 w-[2px]'
                : (i + min - 1) % 5 === 0
                  ? 'h-4 w-px'
                  : 'h-2 w-px'
            ]"
            :style="{
              left: `${((i - 1) / (totalSteps - 1)) * 100}%`,
              transform: 'translateX(-50%)'
            }"
          ></div>
        </template>

        <!-- 添加刻度值标记 -->
        <div
          v-for="val in [-40, -30, -20, -10, 0, 10, 20, 30, 40]"
          :key="val"
          class="absolute top-[-30px] text-xs text-gray-500"
          :style="{
            left: `${((val - min) / (max - min)) * 100}%`,
            transform: 'translateX(-50%)'
          }"
        >
          {{ val }}
        </div>
      </div>

      <!-- 滑块 -->
      <div
        class="absolute top-1/2 -translate-y-1/2 w-4 h-4 rounded-full bg-blue-500 cursor-pointer shadow-md"
        :style="{ left: `${thumbLeft}px` }"
      ></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'

// defineModel 替代 v-model:modelValue
const value = defineModel<number>()

const props = defineProps<{
  min?: number
  max?: number
}>()

const min = props.min ?? -45
const max = props.max ?? 45
const totalSteps = max - min + 1

const sliderRef = ref<HTMLElement | null>(null)
const thumbLeft = ref(0)
const trackRef = ref<HTMLElement | null>(null)

watch(value, () => {
  updateThumbPosition()
})

onMounted(() => {
  updateThumbPosition()
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
})

// 处理窗口大小变化
function handleResize() {
  nextTick(() => {
    updateThumbPosition()
  })
}

function updateThumbPosition() {
  if (!trackRef.value || value.value === undefined) return
  const trackWidth = trackRef.value.clientWidth
  const percent = (value.value - min) / (max - min)
  thumbLeft.value = percent * trackWidth - 8 // 8是滑块宽度的一半
}

function setValueFromClientX(clientX: number) {
  if (!trackRef.value) return

  const rect = trackRef.value.getBoundingClientRect()
  const x = clientX - rect.left
  const percent = Math.max(0, Math.min(1, x / rect.width))
  const newVal = Math.round(min + percent * (max - min))

  value.value = newVal
  updateThumbPosition()
}

function onMouseDown(e: MouseEvent) {
  setValueFromClientX(e.clientX)
  window.addEventListener('mousemove', onMouseMove)
  window.addEventListener('mouseup', onMouseUp)
}

function onMouseMove(e: MouseEvent) {
  setValueFromClientX(e.clientX)
}

function onMouseUp() {
  window.removeEventListener('mousemove', onMouseMove)
  window.removeEventListener('mouseup', onMouseUp)
}

function onTouchStart(e: TouchEvent) {
  setValueFromClientX(e.touches[0].clientX)
  window.addEventListener('touchmove', onTouchMove)
  window.addEventListener('touchend', onTouchEnd)
}

function onTouchMove(e: TouchEvent) {
  setValueFromClientX(e.touches[0].clientX)
}

function onTouchEnd() {
  window.removeEventListener('touchmove', onTouchMove)
  window.removeEventListener('touchend', onTouchEnd)
}
</script>

<style scoped>
/* 可选：添加 hover 效果等美化 */
.bg-blue-500:hover {
  box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.3);
}
</style>
